
gl res "\\micro.intra\Projekt\P0624$\P0624_Gem\Politisk Geografi\Results"
gl dat "\\micro.intra\Projekt\P0624$\P0624_Gem\Politisk Geografi\Data"
gl temp "\\micro.intra\Projekt\P0624$\P0624_Gem\Politisk Geografi\temp"
gl do "\\micro.intra\Projekt\P0624$\P0624_Gem\Politisk Geografi\Dofiler\Replication_v2"

cap log close
log using "$res\log\appendix.log", replace

cd "$temp"
gl e eps // eps pdf


**********************************
*** Mover analysis (Fig A4.1)  ***
**********************************

use "$dat\coordinates.dta", clear

ren id p_id
keep if year==2002 |year==2006 | year==2010
sort p_id year

gen mover =xcoor!=xcoor[_n+1]|  ycoor!=ycoor[_n+1] if p_id ==p_id[_n+1] & year==(year[_n+1]-4)  
gen mover_wm =mover==1 &   llkk==llkk[_n+1] if p_id ==p_id[_n+1] & year==(year[_n+1]-4)
gen mover_om =mover==1 &   llkk!=llkk[_n+1] if p_id ==p_id[_n+1] & year==(year[_n+1]-4)
gen valar=year
joinby p_id valar using "$dat\mun politician data.dta", unmatched(both) 
drop if llkk==.
drop _merge ar nrinom* pers* ripartikod  llkk_2 inval_ord 
gen vald_first =vald==1
sort p_id year
forvalues n=1/5{

replace vald_first=0 if vald[_n-`n']==1 & p_id==p_id[_n-`n']
}
replace vald=0 if vald==.

joinby  p_id  year using "$dat\lisa_togeo.dta", unmatched(master)

keep p_id year llkk dist mover* valar vald_first vald age Kon educ_year parti_initial

do "$do\mun code clean.do" 
merge m:1 dist llkk year using "$dat\main.dta", keepus(em_sh own_sh highq_sh highed_sh *maj2) nogen keep(match master)


ren fpmaj2 fmaj2
ren mpmaj2 gmaj2
ren kdmaj2 kmaj2
gen maj=.
replace parti_initial=lower(parti_initial)
foreach p in m c k f  g s v{
	replace maj=0 if parti_initial=="`p'" 
replace maj=1 if parti_initial=="`p'" & `p'maj2==1 
 }
  


reghdfe mover vald, abs(educ year llkk age)
reghdfe mover vald if mover_om!=1, abs(educ year llkk age)
sort p_id year
foreach var in em highq highed own{

gen mover_aff_`var' =mover==1 &   `var'_sh>=`var'_sh[_n+1] ///
if p_id ==p_id[_n+1]  & `var'_sh!=. & `var'_sh!=.
}

gen age_cat5 = int(age/5)
gen count=1
bysort llkk year: egen kom_adbef= total(count)
gen w_kom_adbef=1/ kom_adbef
drop count kom_adbef
foreach var in em highq highed own{
gen moverlim_aff_`var'  =mover_aff_`var'  if mover_om!=1 & mover==1
}


la var mover "Moved during election period"
la var mover_aff_em "Born in the West"
la var mover_aff_highq "Top income quartile"
la var mover_aff_highed "Tertiary educated"
la var mover_aff_own  "Home owners"

	foreach out in mover mover_aff_em mover_aff_highq mover_aff_highed  mover_aff_own {
preserve
keep `out' mover_om w_kom_adbef vald vald_first maj llkk age_cat5  educ_year


local s=0
matrix C =J(7,6,.)


local s=`s'+1
areg `out' vald if mover_om!=1 [pw= w_kom_adbef],   abs(llkk)
	matrix C[`s',1]=_b[ vald]
	matrix C[`s',2]=(_b[ vald]+1.96*_se[ vald])
	matrix C[`s',3]=(_b[ vald]-1.96*_se[ vald])
	

local s=`s'+1
areg `out'  vald_first if mover_om!=1  [pw= w_kom_adbef],   abs(llkk)
	matrix C[`s',1]=_b[vald_first]
	matrix C[`s',2]=(_b[vald_first]+1.96*_se[vald_first])
	matrix C[`s',3]=(_b[vald_first]-1.96*_se[vald_first])
	


local s=`s'+1
areg `out' maj if vald==1 & mover_om!=1 [pw= w_kom_adbef],   abs(llkk)
	matrix C[`s',1]=_b[maj]
	matrix C[`s',2]=(_b[maj]+1.96*_se[maj])
	matrix C[`s',3]=(_b[maj]-1.96*_se[maj])
	
	local s=`s'+1
reghdfe `out'  vald if mover_om!=1 [pw= w_kom_adbef],   abs(llkk age_cat5 educ_year)
	matrix C[`s',1]=_b[ vald]
	matrix C[`s',2]=(_b[ vald]+1.96*_se[ vald])
	matrix C[`s',3]=(_b[ vald]-1.96*_se[ vald])

	local s=`s'+1
reghdfe `out'  vald_first if mover_om!=1 [pw= w_kom_adbef],   abs(llkk age_cat5 educ_year)
	matrix C[`s',1]=_b[vald_first]
	matrix C[`s',2]=(_b[vald_first]+1.96*_se[vald_first])
	matrix C[`s',3]=(_b[vald_first]-1.96*_se[vald_first])

	
local s=`s'+1
reghdfe `out'  maj if vald==1 & mover_om!=1  [pw= w_kom_adbef],   abs(llkk age_cat5 educ_year)
	matrix C[`s',1]=_b[maj]
	matrix C[`s',2]=(_b[maj]+1.96*_se[maj])
	matrix C[`s',3]=(_b[maj]-1.96*_se[maj])
	

svmat C
sum C*
 ren C1 est
 ren C2 ci_low
 ren C3 ci_high
gen pos_b =4.2-_n if _n<4
gen pos_c =6.8-_n if _n>3 & _n<7
drop if _n>7

loc y  ylabel(	3 `" "Elected vs." "population" "'  ///
	2  `" "First time elected" "vs. population" "' ///
	1 `" "Majority vs." "opposition politicians" "', labsize(large) angle(horizontal))

if "`out'"!="mover" & "`out'"!="mover_aff_em" loc y ylabel(3 " " 2 " " 1 " ")
loc g graphregion(margin(0 0 0 0)) 
if "`out'"!="mover" &  "`out'"!="mover_aff_em" loc g graphregion(margin(40 0 0 0)) 
loc l legend(order(2 "Municipality fixed effects" 4 "Municipality + Age group + Education level fixed effects") rows(1) size(large))
if "`out'"=="mover" loc l legend(off)
twoway (rbar ci_low ci_high pos_b , lwidth(vvthin)  fcolor(black) lcolor(black)  horizontal lpattern(solid) barwidth(.015)) ///
(scatter pos_b est , msize(large)  msymbol(circle)   mcolor(black)) ///
(rbar ci_low ci_high pos_c , lwidth(vvthin)  fcolor(gs8) lcolor(gs8)  horizontal lpattern(solid) barwidth(.015)) ///
(scatter pos_c est , msize(large)  msymbol(circle)   mcolor(gs8)) ///
	,xline(0, lcolor(gs1) lpattern(dash)) 	xlabel(, grid) ytitle(, size(zero))  ///
   ysize(15) xsize(30) scheme(s1mono)yscale(range(0.5 3.5))  xtitle("")  ///
	 yline(1.5 2.5,  lpattern(shortdash) lcolor(gs8)) title("`:var label `out''",size(large)) `y' `g' `l' 
graph save 	move_`out', replace

	restore
	
	}
	
loc set 	scheme(s1mono)	 ysize(5) xsize(7) iscale(1)
graph combine  move_mover.gph ,   `set' 
graph export "$res\figA41a.$e",  replace

grc1leg  move_mover_aff_em.gph  move_mover_aff_highq.gph  move_mover_aff_highed.gph  move_mover_aff_own.gph ///
,  col(4) `set' xcommon b1("Estimated relationship", size(vlarge)) t1("Has moved to neighborhood with more:", size(huge)) ring(2)
graph display,	ysize(5) xsize(20)	
graph export "$res\figA41b.$e",  replace	 
	
*check numbers
sum mover [aw= w_kom_adbef]  if mover_om!=1  // 0.19
sum mover [aw= w_kom_adbef]  if vald==1 &  mover_om!=1 // 0.13
sum mover [aw= w_kom_adbef]  if vald_first==1 &  mover_om!=1 // 0.15

************************************************
** Figur för k-neighborhoods (fig A5:1 A5:2)****
************************************************

**** Advantage: all ***
use "$dat\temp\Highq_all.dta", clear
sort id k
merge 1:1 id k using "$dat\temp\Highed_all.dta"
drop _merge
sort id k
merge 1:1 id k using "$dat\temp\Ethnic_majority_all.dta"
drop _merge
merge 1:1 id k using "$dat\temp\precinct.dta"
drop _merge
drop if k==100
drop if k==2000

la var Highq "Top income quartile"
la var Ethnic_majority "Born in the West"
la var Highed "Tertiary educated"
twoway (scatter Highq Highed Ethnic_majority k, msize(medlarge) msymbol(circle) mcolor(black) ),	 xtitle("K-nearest neighbors", size(medium))  xlabel(50 500 1000 1500 "Precinct")  ytitle("politicians/non-politicians", size(medium)) l1title(Ratio) scheme(s1mono)  ylabel(1.00(0.05)1.15, grid) title("All politicians") ///
xscale(range(20 1600))legend(rows(1) size(large))

graph save k_nearest_all, replace

**** Advantage: left ***
use "$dat\temp\Highq_left.dta", clear
sort id k
merge 1:1 id k using "$dat\temp\Highed_left.dta"
drop _merge
sort id k
merge 1:1 id k using "$dat\temp\Ethnic_majority_left.dta"
drop _merge
merge 1:1 id k using "$dat\temp\precinct_left.dta"
drop _merge
drop if k==100
drop if k==2000

la var Highq "Top income quartile"
la var Ethnic_majority "Born in the West"
la var Highed "Tertiary educated"
twoway (scatter Highq Highed Ethnic_majority k, msize(medlarge) msymbol(circle) mcolor(black)),	xlabel(50 500 1000 1500 "Precinct") ytitle("") scheme(s1mono)   xtitle("K-nearest neighbors", size(medium)) ylabel(1 " " 1.05 " " 1.10 " "  1.15 " ", grid)  xscale(range(20 1600)) title(Left bloc politicians) 
graph save  k_nearest_left, replace


**** Advantage: right ***
use "$dat\temp\Highq_right.dta", clear
sort id k
merge 1:1 id k using "$dat\temp\Highed_right.dta"
drop _merge
sort id k
merge 1:1 id k using "$dat\temp\Ethnic_majority_right.dta"
drop _merge
merge 1:1 id k using "$dat\temp\precinct_right.dta"
drop _merge
drop if k==100
drop if k==2000

la var Highq "Top income quartile"
la var Ethnic_majority "Born in the West"
la var Highed "Tertiary educated"
twoway (scatter Highq Highed Ethnic_majority k, msize(medlarge) msymbol(circle) mcolor(black)),	xlabel(50 500 1000 1500 "Precinct") ytitle("") scheme(s1mono) xtitle("K-nearest neighbors", size(medium))  ylabel(1 " " 1.05 " " 1.10 " " 1.15 " ", grid)  xscale(range(20 1600)) title(Center-right bloc politicians) 
graph save k_nearest_right, replace


**** Disdvantage: all ***
use "$dat\temp\Lowq.dta", clear
sort id k
merge 1:1 id k using "$dat\temp\Lowed.dta"
drop _merge
sort id k
merge 1:1 id k using "$dat\temp\Ethnic_minority.dta"
drop _merge
merge 1:1 id k using "$dat\temp\precinct_disadvantaged.dta"
drop _merge
drop if k==100
drop if k==2000
scatter Lowq Lowed Ethnic_minority k

la var Lowq "Not top income quartile"
la var Ethnic_minority "Not born in the West"
la var Lowed "Not tertiary educated"
twoway (scatter Lowq Lowed Ethnic_minority k, msize(medlarge) msymbol(circle) mcolor(black)),	xlabel(50 500 1000 1500 "Precinct")  ytitle("politicians/non-politicians", size(medium)) l1title(Ratio) scheme(s1mono) xtitle("K-nearest neighbors", size(medium))  title("All politicians")  ylabel(0.70(0.1)1.0, grid) xscale(range(20 1600)) legend(rows(1) size(large)) 
graph save k_nearest_disadvantaged, replace

**** Disdvantage: left ***
use "$dat\temp\Lowq_left.dta", clear
sort id k
merge 1:1 id k using "$dat\temp\Lowed_left.dta"
drop _merge
sort id k
merge 1:1 id k using "$dat\temp\Ethnic_minority_left.dta"
drop _merge
merge 1:1 id k using "$dat\temp\precinct_disadvantaged_left.dta"
drop _merge
drop if k==100
drop if k==2000
scatter Lowq Lowed Ethnic_minority k

la var Lowq "Not top income quartile"
la var Ethnic_minority "Not born in the West"
la var Lowed "Not tertiary educated"
twoway (scatter Lowq Lowed Ethnic_minority k, msize(medlarge) msymbol(circle) mcolor(black)),	xlabel(50 500 1000 1500 "Precinct") ytitle(" ") scheme(s1mono) xtitle("K-nearest neighbors", size(medium))   ylabel(0.7 " " 0.8 " " 0.9 " " 1.00 " ", grid) xscale(range(20 1600)) title("Left bloc politicians")
graph save k_nearest_disadvantaged_left, replace


**** Disdvantage: right ***
use "$dat\temp\Lowq_right.dta", clear
sort id k
merge 1:1 id k using "$dat\temp\Lowed_right.dta"
drop _merge
sort id k
merge 1:1 id k using "$dat\temp\Ethnic_minority_right.dta"
drop _merge
merge 1:1 id k using "$dat\temp\precinct_disadvantaged_right.dta"
drop _merge
drop if k==100
drop if k==2000
scatter Lowq Lowed Ethnic_minority k

la var Lowq "Not top income quartile"
la var Ethnic_minority "Not born in the West"
la var Lowed "Not tertiary educated"
twoway (scatter Lowq Lowed Ethnic_minority k, msize(medlarge) msymbol(circle) mcolor(black)),	xlabel(50 500 1000 1500 "Precinct") ytitle(" ") scheme(s1mono) xtitle("K-nearest neighbors", size(medium))  title("Center-right bloc politicians") ylabel(0.7 " " 0.8 " "  0.9 " " 1.00 " ", grid) xscale(range(20 1600))  graphregion(margin(0 5 2 2)) 
graph save k_nearest_disadvantaged_right, replace

********************************************
********* combine figures  A5.1 A5.2  ******
********************************************

grc1leg k_nearest_all.gph k_nearest_left.gph k_nearest_right.gph, col(3) iscale(1.25)  ysize(15) xsize(50)	  scheme(s1mono)
graph display,  ysize(15) xsize(50)
graph export "$res\figA51.$e",  replace

grc1leg k_nearest_disadvantaged.gph k_nearest_disadvantaged_left.gph k_nearest_disadvantaged_right.gph, col(3) iscale(1.25)  ysize(15) xsize(50)	  scheme(s1mono)
graph display,  ysize(15) xsize(50)
graph export "$res\figA52.$e",  replace


************************************************************************
*** For replication of results in paper: Oster-results (Table A8.1)  ***
************************************************************************

use "$dat\main.dta", clear

gl pop_cont diff_highq_bef diff_highed_bef diff_own_bef diff_em_bef  diff_retired_bef diff_child_7_15_bef
gl turnout_cont diff_voters_bef
gl ecgeo_cont diff_b_area_multi diff_b_area_single  pop_dens_mdiff floorarea_pc_mdiff 
 
reg diff_area_multi_bef diff_maj_min $pop_cont $turnout_cont $ecgeo_cont diff_area_multi_lag_bef [pw=w_dist_count] if close==1
* R2= 0.183  ; 1.3*R2=0.238  ; 1.6*R2=0.293
psacalc beta diff_maj_min, rmax(0.238) //B uncontrolled: -0.174 (0.006) B controlled: -0.132 (0.195) Bound: -0.122 
psacalc beta diff_maj_min, rmax(0.293) //Bound: -0.109

reg diff_area_multi_bef diff_maj_min $pop_cont $turnout_cont $ecgeo_cont   diff_area_multi_lag_bef [pw=w_dist_count] if cl_bl==1
* R2= 0.195  ; 1.3*R2=0.254  ; 1.6*R2=0.312
psacalc beta diff_maj_min, rmax(0.254) //B uncontrolled: -0.174 (0.006) B controlled: -0.132 (0.195) Bound: -0.118 
psacalc beta diff_maj_min, rmax(0.312) //Bound: -0.105


	
******************************
*** Figures A8.1    ****
******************************

*define control variables

gl pop_cont_std std_diff_highq_bef std_diff_highed_bef std_diff_own_bef std_diff_em_bef  std_diff_retired_bef std_diff_child_7_15_bef
gl turnout_cont_std std_diff_voters_bef
gl ecgeo_cont_std std_diff_b_area_multi std_diff_b_area_single  std_pop_dens_mdiff std_floorarea_pc_mdiff 
gl lagg_std std_diff_area_single_lag_bef  std_diff_area_multi_lag_bef 


foreach treat in  diff_maj_min {
foreach sample in cl_bl all close {
preserve
local s=0
matrix C =J(22,6,.)

foreach var  in  $pop_cont_std {
local s=`s'+1
reg `var' `treat'  if `sample'==1 [pw= w_dist_count],  cluster(llkk)
	matrix C[`s',1]=_b[ `treat']
	matrix C[`s',2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[`s',3]=(_b[ `treat']-1.96*_se[ `treat'])
}

local s=`s'+2

foreach var  in   $turnout_cont_std {
local s=`s'+1
reg `var' `treat'  if `sample'==1 [pw= w_dist_count],  cluster(llkk)
	matrix C[`s',1]=_b[ `treat']
	matrix C[`s',2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[`s',3]=(_b[ `treat']-1.96*_se[ `treat'])
}

local s=`s'+2 //+2


foreach var  in  	$ecgeo_cont_std std_ln_price_sqm_old_mdiff {

local s=`s'+1
reg `var' `treat'  if `sample'==1  [pw=w_dist_count],  cluster(llkk)
	matrix C[`s',1]=_b[ `treat']
	matrix C[`s',2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[`s',3]=(_b[ `treat']-1.96*_se[ `treat'])
}



local s=`s'+2 //+2

foreach var  in   $lagg_std     {
local s=`s'+1

reg `var' `treat'  if `sample'==1  [pw= w_dist_count],  cluster(llkk)
	matrix C[`s',1]=_b[ `treat']
	matrix C[`s',2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[`s',3]=(_b[ `treat']-1.96*_se[ `treat'])

}

local s=`s'+1

svmat C
sum C*
 ren C1 est
 ren C2 ci_low
 ren C3 ci_high
gen pos =21-_n 


if "`sample'"=="all"  loc t "All elections"
if "`sample'"=="close"  loc t "Close elections"
if  "`sample'"=="cl_bl"  loc t "Close elections, no dominant bloc"

if "`sample'"=="all"  loc y ylabel(20 "Top income quartile" 19 "Tertiary educated" 18 "Non-immigrant"  ///
	 17  "Homeowner" 16 "Age 65+ years" 15 "Children 7-15 years" ///
	 12  "Voted in election"  ///
	9 "Existing m.f. homes"	8 "Existing s.f. homes " ///
	7 "Population density" 6 "Floor area per capita"  ///
	5 "Housing prices"   ///
	2 "Permit m.f. homes" 1 "Permit s.f. homes"  , labsize(medsmall) angle(horizontal)) ///
	ymlabel(21 "{bf:Population}" 13 "{bf:Turnout}" 10 "{bf:Economic geography}" 3 "{bf: Lagged variables}", ///
	labsize(medsmall) angle(horizontal) tlcolor(white) ) 
else loc y ylabel(20 " " 19 " " 18 " " 17 " " 16 " " 15 " " 12 " " 9 " " 8 " " 7 " " 6 " "  5 " " 2 " " 1 " ")	
loc x graphregion(margin(l=0 r=0))
if "`sample'"=="close" loc x   graphregion(margin(l=13 r=10))	
if  "`sample'"=="cl_bl" loc x  graphregion(margin(l=3 r=20))	

drop if _n>20 
tab pos
twoway (rbar ci_low ci_high pos , lwidth(vvthin)  fcolor(black) lcolor(black)  horizontal lpattern(solid) barwidth(.015)) ///
(scatter pos est , msize(medlarge)  msymbol(circle)   mcolor(black)) ///
	,xline(0, lcolor(gs1) lpattern(dash)) xlabel(, grid) ///
  scale(.7) `x' scheme(s1mono) yscale(range(0.5 21.5)) ytitle(, size(zero))  title("`t'" , size(medlarge))  ///
	legend(off) `y'ysize(15) xsize(20) 

graph save `treat'_balance_`sample', replace

	restore
	
	}
	}


 	
	graph combine  diff_maj_min_balance_all.gph  diff_maj_min_balance_close.gph diff_maj_min_balance_cl_bl.gph, col(3) iscale(1.1) ///
	scheme(s1mono)	 ysize(9) xsize(20)	b1("Estimated relationship with the treatment variable (the difference in residential" "concentration of majority and opposition politicians)", size(medium)) xcommon
graph export "$res\figA81.$e", replace	




	 
**********************	  
****  Figure A9.1  ***
**********************
	  
		  
	 foreach var in area_multi area_single {
	foreach sample in all bl {
preserve
	matrix B = J(95,4,.)
gen treat =diff_maj_min
	forvalues n=1/95{
	 scalar bandwidth = `n'/1000+0.005
		  reg diff_`var'_bef treat [pw=w_dist_count ] if ( `sample'==1 & abs(dist_h_simp) <bandwidth| abs(dist_v_simp) <bandwidth) ,cluster(llkk)
			matrix B[`n',1] = _b[treat]
			matrix B[`n',2] = _b[treat] + 1.96*_se[treat]
			matrix B[`n',3] = _b[treat] - 1.96*_se[treat]
			matrix B[`n',4] = bandwidth
		}
	svmat B
	rename B1 estimate
	rename B2 upper
	rename B3 lower
	rename B4 bandwidth
	
if "`sample'"=="all" loc t "All election"
if "`sample'"=="bl" loc t "Elections with no dominant bloc"
if "`var'"=="area_multi" loc x title("`t'") xlabel(, nolabels)
if "`var'"=="area_single" 	loc x title("") 
if "`sample'"=="bl" loc y ylabel(-0.4 "" -0.2 "" 0 "" 0.2 ""  , nolabels grid) graphregion(margin(5 0 0 0))
if "`sample'"=="all"  loc y   ylabel( -0.4 "-.4" -0.2 "-.2" 0 "0" 0.2 ".2" , angle(horizontal) grid) graphregion(margin(0 0 0 0))
	
	graph twoway line estimate upper lower bandwidth, lc(gs0 gs0 gs0) lp(solid shortdash shortdash) ///
		 xline(0.05, lcolor(gs1) lpattern(shortdash)) yline(0, lcolor(gs7) lpattern(dash))  xtitle("") ///
	 ytitle("")    scheme(s1mono) ///
	 legend(on order(1 "Point estimate" 2 "95% confidence interval")  rows(1) size(small)) ///
	  `x' `y' yscale(range(-0.5 0.3)) xscale(range(0 0.1))
		graph save bw_`sample'_`var', replace
restore
}
}	
	
loc set 	col(2) iscale(0.9) scheme(s1mono)	 ysize(11) xsize(20) xcommon 
grc1leg  bw_all_area_multi.gph bw_bl_area_multi.gph , `set' ///
t1("Approved permits for multi-family homes (sqm)", size(large))
graph save temp1, replace

grc1leg 	bw_all_area_single.gph bw_bl_area_single.gph, `set' ///
t1("Approved permits for single-family homes (sqm)", size(large))
graph save temp2, replace	
	
	
grc1leg temp1.gph temp2.gph, row(2)	scheme(s1mono) b1("Window used to define close elections", size(small)) iscale(.75) ring(2) l1("Estimated treatment effect", size(small))
graph display, xsize(17) ysize(10)	
	
graph export "$res\figA91.$e", replace	

***********************
***   Table A9.1    ***
***********************
cd "$res" 


gl add b(3) nonotes nogaps se(3) label nocons star(* 0.1 ** 0.05 *** 0.01) booktabs fragment nonum ///
indicate( "Full set of controls=diff_b_area_multi_bef"   ,l(\checkmark)) nomtitles

loc cont  $pop_cont $turnout_cont $ecgeo_cont  	 diff_area_multi_lag_bef

 
eststo clear
ren diffalt_maj_min_vald_ab15sm var1
ren diffalt_maj_min_vald_bel15sm var2
eststo:	 reg diff_area_multi_bef  var1 var2   [pw=w_dist_count ]  ,  cluster(llkk)
eststo:	 reg diff_area_multi_bef var1 var2  `cont'	 		[pw=w_dist_count ] ,  cluster(llkk)

ren var1 diffalt_maj_min_vald_ab15sm 
ren var2 diffalt_maj_min_vald_bel15sm 

ren diffalt_maj_min_vald_rel var1
ren	diffalt_maj_min_vald_norell var2	
		
eststo: reg diff_area_multi_bef   var1 var2  [pw=w_dist_count ]  ,  cluster(llkk)
eststo:	reg diff_area_multi_bef var1 var2	 `cont' [pw=w_dist_count ]   ,  cluster(llkk)

ren var1 diffalt_maj_min_vald_rel 
ren	var2 diffalt_maj_min_vald_norell 

ren diffalt_maj_min_vald_coll  var1
ren diffalt_maj_min_vald_nocoll var2

eststo: reg diff_area_multi_bef var1 var2    [pw=w_dist_count ]  ,  cluster(llkk)	
eststo: reg diff_area_multi_bef  var1 var2 	`cont'  [pw=w_dist_count ]  ,  cluster(llkk)
esttab using "tabA91.tex",  replace keep(var1 var2 ) mgroups("Residence $>$ 15 years"   "\makecell{At least one parent \\ or sibling}" "At least one colleague", pattern(1 0 1  0 1 0) prefix(\multicolumn{2}{c}{) suffix(}) span  ) $add  coef(var1 "Stong ties" var2 "Weak ties" ) 

				 
ren var1 diffalt_maj_min_vald_coll  
ren var2 diffalt_maj_min_vald_nocoll 
	

	
********************
****  Table A1   ***
********************

replace pop_dens=pop_dens*1000000 // transform to sq km

la var bef Population
la var highq "Top income quartile"
la var highed "Tertiary education"
la var em  "Born in the West"
la var own "Home owners"
la var retired Retired
la var child_7_15 "Children age 7-15"
la var votes "Voters"
la var b_area_multi "Existing multi-family house (sqm)"
la var b_area_single "Existing single-family house (sqm)"
la var area_multi "Permits multi-family house (sqm)"
la var area_single "Permits single-family house (sqm)"
la var pop_dens "Population density (sq km)"
la var floorarea_pc "Floor area per capita"
la var ln_price_sqm_old "ln(Price per sqm)"
la var vald_maj "Political majority"
la var vald_min "Political minority"

cd "$res" 
eststo clear 
eststo: estpost sum bef highq  highed  em  own retired child_7_15  votes pop_dens  floorarea_pc  b_area_multi b_area_single area_multi area_single ln_price_sqm_old vald_maj vald_min if all==1 [aw=w_dist_count]
esttab using "tabA1.tex", replace wide cells("mean(fmt(1)) count(fmt(0))") nonotes nonum noobs ///
nomtitle label fragment
				 

********************
**** Table A3-A4 ***
********************




gl add b(3) nonotes nogaps se(3) label nocons star(* 0.1 ** 0.05 *** 0.01) booktabs fragment nonum

gl add1 replace $add collabels(none) nolines noobs
gl add2 append $add nonum nomtitle mlabels(none) nolines noobs
gl add3 append $add nonum nomtitle mlabels(none) 

gl spec [pw=w_dist_count ] 

gl samp all   close cl_bl


*check correlation permits and econ geo
reg diff_area_multi_bef  $ecgeo_cont // strong correlation

cd "$res"
loc treat diff_maj_min
foreach var  in   area_single  area_multi {
if "`var'"=="area_multi" loc tab A3
else loc tab A4	
	
eststo clear
foreach sample in  $samp  {
eststo: reg diff_`var'_bef `treat'  $spec if `sample' ==1  ,cluster(llkk)
loc num_`sample'=e(N)
}
esttab using "tab`tab'.tex",  keep(`treat' ) $add1  coef(`treat'  "\hline No control") mtitle(All   "Close margin" "\makecell{ Close margin \\ no dominant bloc}")


eststo clear
foreach sample in  $samp {
eststo: reg diff_`var'_bef `treat'	$pop_cont $spec if `sample' ==1 ,cluster(llkk)
}
esttab using "tab`tab'.tex", keep(`treat' ) $add2  coef(`treat'  "Population composition")

eststo clear
foreach sample in  $samp {
eststo: reg diff_`var'_bef `treat' $turnout_cont $spec if `sample' ==1 ,cluster(llkk)
}
esttab using "tab`tab'.tex", keep(`treat' ) $add2 coef(`treat'  "Turnout")
	
eststo clear	
foreach sample in  $samp {
eststo:reg diff_`var'_bef `treat'    $ecgeo_cont $spec if `sample' ==1, cluster(llkk)
}
esttab using "tab`tab'.tex", keep(`treat' ) $add2 coef(`treat'  "Economic geography")
	
eststo clear	
foreach sample in  $samp {
eststo: reg diff_`var'_bef `treat'  diff_`var'_lag_bef  $spec if `sample' ==1 ,cluster(llkk)
}
esttab using "tab`tab'.tex", keep(`treat' ) $add2  coef(`treat'  "Lagged dependent variable")

eststo clear
foreach sample in  $samp {
eststo: reg diff_`var'_bef `treat'  diff_`var'_lag_bef  $ecgeo_cont $turnout_cont	$pop_cont  $spec if `sample' ==1 ,cluster(llkk)
}
esttab using "tab`tab'.tex", keep(`treat' ) $add3 nolines stat(N , fmt(0) labels(" Observations with all controls"))		coef(`treat'  "All controls")	prefoot( "\hline Observations with no controls & `num_all' & `num_close' & `num_cl_bl' \\" )
}		
	
*******************************
*** Fuzzy RDD table A92-A93  ****
*******************************


gen left_inst= vanster_maj*diff_vald_left_right
gen right_inst= -hoger_maj*diff_vald_left_right
gen right_force=-dist_h_simp*diff_vald_left_right
gen left_force=dist_v_simp*diff_vald_left_right
gen right_force_sq=right_force^2
gen left_force_sq=left_force^2
gen right_force_cub=right_force^3
gen left_force_cub=left_force^3


la var left_inst "Left seat maj.*left-right conc."
la var right_inst "Right seat maj.*right-left conc." 
la var diff_maj_min "Majority-opposition conc."
gl add b(3) nonotes nogaps se(3) label nocons star(* 0.1 ** 0.05 *** 0.01) booktabs fragment 

gl add1 replace $add collabels(none) nomtitle  nolines noobs 
gl add2 append $add nonum nomtitle mlabels(none) nolines noobs
gl add3 append $add nonum nomtitle mlabels(none) nolines


foreach y in  multi single {
	
if "`y'"=="multi" loc tab A92
else loc tab A93
	
loc var1 diff_vald_left_right left_force right_force 
loc var2 diff_vald_left_right left_force right_force left_force_sq right_force_sq
loc var3 diff_vald_left_right left_force right_force left_force_sq right_force_sq  left_force_cub right_force_cub
loc spec [pw=w_dist_count ]  if all==1 & !mi(diff_area_`y'_bef) & !mi(diff_maj_min), cluster(llkk_year) 

*** first stage ***
cd "$res"



eststo clear
eststo: reg diff_maj_min left_inst  diff_vald_left_right   [pw=w_dist_count ] if  abs(dist_v_simp) <.05 & !mi(diff_area_`y'_bef), cluster(llkk) // 7721 obs
eststo:    reg diff_maj_min right_inst  diff_vald_left_right [pw=w_dist_count ] if  abs(dist_h_simp) <.05 & !mi(diff_area_`y'_bef), cluster(llkk) //6996 obs
eststo:   reg diff_maj_min  right_inst left_inst `var1'  `spec' // 15557 obs
eststo:  reg diff_maj_min  right_inst left_inst `var2' `spec' // 15557
eststo:  reg  diff_maj_min  right_inst left_inst `var3'   `spec' // 15557
esttab using "tab`tab'.tex",  keep(left_inst right_inst ) $add1  refcat(left_inst "First stage: ", nolabel)

 
 
*** reduced form  ***
 eststo clear
eststo: reg diff_area_`y'_bef left_inst  diff_vald_left_right [pw=w_dist_count ] if  abs(dist_v_simp) <.05 & !mi(diff_maj_min), cluster(llkk) // 8317
eststo:  reg diff_area_`y'_bef right_inst  diff_vald_left_right [pw=w_dist_count ] if  abs(dist_h_simp) <.05  & !mi(diff_maj_min), cluster(llkk) // 7300
eststo:   reg diff_area_`y'_bef   right_inst left_inst `var1'  `spec' // 16986
eststo:   reg diff_area_`y'_bef   right_inst left_inst `var2'  `spec'	 
eststo:  reg  diff_area_`y'_bef  right_inst left_inst `var3'  `spec' 
esttab using "tab`tab'.tex",  keep(left_inst right_inst ) $add2  coef(left_inst "\hline Reduced form: \\ Left seat maj.*left-right conc." ) refcat(right_inst "\hline  IV:", nolabel below) 

  
*** 2SLS multi ***

eststo clear
eststo:  ivreg2 diff_area_`y'_bef (diff_maj_min=left_inst )  diff_vald_left_right [pw=w_dist_count ] if  abs(dist_v_simp) <.05, cluster(llkk) // 7643 
eststo:  ivreg2 diff_area_`y'_bef (diff_maj_min =right_inst )  diff_vald_left_right [pw=w_dist_count ] if  abs(dist_h_simp) <.05, cluster(llkk) // 6938
eststo:  ivreg2 diff_area_`y'_bef  (diff_maj_min =right_inst left_inst) `var1'  `spec' // 15432
eststo:   ivreg2 diff_area_`y'_bef  (diff_maj_min =right_inst left_inst) `var2'  `spec' 
eststo:    ivreg2 diff_area_`y'_bef  (diff_maj_min =right_inst left_inst) `var3'  `spec'  
esttab using "tab`tab'.tex",  keep(diff_maj_min ) $add3  refcat(diff_maj_min "\hline Instrument & Left & Right & Both & Both & Both \\ Left threshold & \checkmark & & & &   \\ Right threshold &  & \checkmark  ", nolabel below)  indicate( "Global control 1st pol.=left_force" "Global control 2nd pol.=left_force_sq"  "Global control 3d pol.=left_force_cub"  ,l(\checkmark)) 

}


********************************
***** Histogram A1,A3,A8,A9  ***
********************************

cd "$temp"

egen tag_mun_year=tag(llkk year)

* fig A1
loc set scheme(s1mono) bin(100) ysize(12) xsize(20) graphregion(margin(0 0 0 0)) scale(1.2) ///
fraction ylabel(, angle(horizontal) grid) ytitle("")

hist adbef [fweight = f_dist_count]  ,  `set' xtitle(Adult citizens (18+) per neighborhood)  
graph save precinctpop_hist, replace

hist dist_count if  tag==1 , `set' xtitle(Number of neighborhoods per municipality) 
 graph save precinctno_hist, replace

graph combine  precinctpop_hist.gph  precinctno_hist.gph, scheme(s1mono) col(2) ysize(7) xsize(20) iscale(1) ///
 l1title(Fraction)
graph export "$res\figA1.$e", replace


*fig A3
la var own homeowners
la var highed "teritiary educated"
la var em "born in the West"
la var highq "top income quartile"

foreach var in highq em own highed {
 hist diff_`var'_bef [fweight = f_dist_count] , scheme(s1mono) bin(100) ///
 ysize(12) xsize(20) graphregion(margin(0 0 0 0))  scale(1.2) fraction ///
 xtitle(Concentration of `:var label `var'' )  ylabel(, angle(horizontal) grid) ytitle("") 
graph save hist_`var', replace
}

loc set scheme(s1mono) ysize(13) xsize(20) iscale(.9)
graph combine  hist_highq.gph hist_highed.gph, `set'  l1title(Fraction) col(2) 
graph save temp1, replace
graph combine hist_em.gph hist_own.gph, `set'  l1title(Fraction) col(2) 
graph save temp2, replace
graph combine temp1.gph temp2.gph, `set' row(2)
graph export "$res\figA3.$e",  replace


*fig A8-A9
loc set scheme(s1mono) bin(100) ysize(12) xsize(20) scale(1.2) fraction ylabel(, angle(horizontal) grid) ///
graphregion(margin(0 0 0 0)) ytitle("")

hist diff_area_multi_bef [fweight = f_dist_count], freq
hist diff_area_multi_bef [fweight = f_dist_count],  `set' xtitle(Concentration of building permits for  multi-family home permits)  
graph save hist_multi, replace


hist diff_area_single_bef [fweight = f_dist_count] ,  `set' xtitle(Concentration of building permits for single-family home permits)  
graph save hist_single, replace

graph combine  hist_multi.gph  hist_single.gph, scheme(s1mono) col(2) ysize(7) xsize(20) iscale(1)  l1title(Fraction)
graph export "$res\figA8.$e",  replace

 hist diff_maj_min [fweight = f_dist_count] , `set' xtitle("Difference in neighborhood concentration of" "majority vs opposition politicians" )  
graph export "$res\figA9.$e",  replace



*********************
** *	Figure A6 ***
*********************
			foreach sample in all  {
	preserve
local s=0
matrix C =J(8,6,.)

	foreach p in  m c k f  g s v {
local s=`s'+1
reg votes_`p'_sh_mdiff  vald_`p'_sh_mdiff if `sample'==1 [aw= w_dist_count], cluster(llkk)
sum votes_`p'_sh_mdiff  if vald_`p'_sh_mdiff!=. & `sample'==1 [aw= w_dist_count]
local sdy=r(sd) 
sum vald_`p'_sh_mdiff  if votes_`p'_sh_mdiff!=. & `sample'==1 [aw= w_dist_count]
local sdx=r(sd) 
	matrix C[`s',1]=(_b[ vald_`p'_sh_mdiff ])*`sdx'/`sdy'
	matrix C[`s',2]=(_b[ vald_`p'_sh_mdiff ]+1.96*_se[vald_`p'_sh_mdiff ])*`sdx'/`sdy'
	matrix C[`s',3]=(_b[ vald_`p'_sh_mdiff ]-1.96*_se[ vald_`p'_sh_mdiff ])*`sdx'/`sdy'
matlist C
	}
svmat C
sum C*
 ren C1 est
	ren C2 ci_low
	ren C3 ci_high

gen pos =_n
list pos est if !mi(est)
drop if _n>7
tab pos
twoway (scatter pos est , msize(medlarge)  msymbol(circle)   mcolor(black)) ///
(rbar ci_low ci_high pos , lwidth(vvthin)  fcolor(gs1) lcolor(gs1) lpattern(solid) horizontal barwidth(.015)) ///
	,xline(0, lcolor(gs1) lpattern(dash)) 	xlabel(, grid) ytitle(, size(zero))  ///
  scale(1) ysize(15) xsize(20) scheme(s1mono)yscale(range(0.5 7.5))  ///
  xtitle("Estimated relationship between share of the" "party's voters and the share of the party's politicians" "in the neighboorhood population (beta coefficients)", size(medium))  ///
	ylabel(	 1 "Conservative Party"  2 "Center Party" ///
	 3 "Christian Democrats" 4 "Liberal Party"  5 "Green Party"  ///
	 6 "Social Democrats" 7 "Left Party" ///
	, labsize(medsmall) angle(horizontal))  legend(off) xscale(range(0 0.7))	xlabel(0(0.1)0.7, grid)
graph save 	polvotes_`sample'_sh, replace

	restore
	
	}
	
	foreach sample in all  {
	foreach pol in vald  {
preserve
local s=0
matrix C =J(7,6,.)

foreach var  in highq highed em own  {
local s=`s'+1

reg  `var'_sh_mdiff `pol'_sh_mdiff  if `sample'==1 [aw= w_dist_count], cluster(llkk)
sum `var'_sh_mdiff  if `pol'_sh_mdiff!=. & `sample'==1 [aw= w_dist_count]
local sdy=r(sd) 
sum `pol'_sh_mdiff   if `var'_sh_mdiff!=. & `sample'==1 [aw= w_dist_count]
local sdx=r(sd) 

	matrix C[`s',1]=(_b[ `pol'_sh_mdiff])*`sdx'/`sdy'
	matrix C[`s',2]=(_b[ `pol'_sh_mdiff]+1.96*_se[`pol'_sh_mdiff])*`sdx'/`sdy'
	matrix C[`s',3]=(_b[`pol'_sh_mdiff]-1.96*_se[`pol'_sh_mdiff])*`sdx'/`sdy'



}


svmat C
sum C*
 ren C1 est
	ren C2 ci_low
	ren C3 ci_high
gen pos =5-_n

drop if _n>4
tab pos
twoway (scatter pos est , msize(medlarge)  msymbol(circle)   mcolor(black)) ///
(rbar ci_low ci_high pos , lwidth(vvthin)  fcolor(gs1) lcolor(gs1) lpattern(solid) horizontal barwidth(.015)) ///
	,xline(0, lcolor(gs1) lpattern(dash)) 	xlabel(, grid) ytitle(, size(zero))  ///
  scale(1) ysize(15) xsize(20) scheme(s1mono)yscale(range(0.5 4.5))  xtitle("Estimated relationship with share of the advataged" "group and the share of politicians in the" "neighboorhood population  (beta coefficients)", size(medium))  ///
	ylabel(	4 "Top income quartile" 3 "Tertiary educated"  ///
	 2 "Born in the West" 1 "Home owner" ///
	, labsize(medsmall) angle(horizontal))  legend(off)
graph save 	aff_`pol'_`sample'_sh, replace

	restore
	
	}
	}	
	
	
	graph combine 	aff_vald_all_sh.gph polvotes_all_sh.gph, col(2) iscale(1.2) scheme(s1mono)	 ysize(7) xsize(20)	imargin(r=10)

graph export "$res\figA6.$e",  replace	




********************
***   Fig A11    ***
********************

	foreach treat in  diff_vald_maj_bef {
foreach var  in   area_single   area_multi  {
	foreach sample in  all {
 preserve
	local s=0
	matrix C =J(1,3,.)
	local s=`s'+1
	reg diff_`var'_bef `treat'   [pw=w_dist_count ] if `sample' ==1 ,cluster(llkk)
	matrix C[1,1]=_b[ `treat']
	matrix C[1,2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[1,3]=(_b[ `treat']-1.96*_se[ `treat'])

	svmat C
	ren C1 est_`s'
	ren C2 ci_low_`s'
	ren C3 ci_high_`s'
	gen pos_`s'=6 if est_`s'!=.
	
	*****
	matrix C =J(1,3,.)
	local s=`s'+1
	reg diff_`var'_bef `treat'  $pop_cont [pw=w_dist_count ] if `sample' ==1 ,  cluster(llkk)
	matrix C[1,1]=_b[ `treat']
	matrix C[1,2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[1,3]=(_b[ `treat']-1.96*_se[ `treat'])

	svmat C
	ren C1 est_`s'
	ren C2 ci_low_`s'
	ren C3 ci_high_`s'
	gen pos_`s'=5 if est_`s'!=.
	
	
		*****
	matrix C =J(1,3,.)
	local s=`s'+1
	reg diff_`var'_bef `treat'   $turnout_cont  [pw=w_dist_count ] if `sample' ==1 ,  cluster(llkk)
	matrix C[1,1]=_b[ `treat']
	matrix C[1,2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[1,3]=(_b[ `treat']-1.96*_se[ `treat'])

	svmat C
	ren C1 est_`s'
	ren C2 ci_low_`s'
	ren C3 ci_high_`s'
	gen pos_`s'=4 if est_`s'!=.
	
	****
	local s=`s'+1
    reg diff_`var'_bef `treat'    $ecgeo_cont   [pw=w_dist_count ] if `sample' ==1 ,  cluster(llkk)
	matrix C[1,1]=_b[ `treat']
	matrix C[1,2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[1,3]=(_b[ `treat']-1.96*_se[ `treat'])


	svmat C
	ren C1 est_`s'
	ren C2 ci_low_`s'
	ren C3 ci_high_`s'
	gen pos_`s'=3 if est_`s'!=.
	
	****
	local s=`s'+1
    reg diff_`var'_bef `treat'    diff_`var'_lag_bef [pw=w_dist_count ] if `sample' ==1 ,  cluster(llkk)
	matrix C[1,1]=_b[ `treat']
	matrix C[1,2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[1,3]=(_b[ `treat']-1.96*_se[ `treat'])

	svmat C
	ren C1 est_`s'
	ren C2 ci_low_`s'
	ren C3 ci_high_`s'
	gen pos_`s'=2 if est_`s'!=.
	****
	
	local s=`s'+1
	reg diff_`var'_bef `treat'    diff_`var'_lag_bef $pop_cont  $turnout_cont  $ecgeo_cont  ///
		 [pw=w_dist_count ] if `sample' ==1 ,   cluster(llkk)
	matrix C[1,1]=_b[ `treat']
	matrix C[1,2]=(_b[ `treat']+1.96*_se[ `treat'])
	matrix C[1,3]=(_b[ `treat']-1.96*_se[ `treat'])

	svmat C
	ren C1 est_`s'
	ren C2 ci_low_`s'
	ren C3 ci_high_`s'
	gen pos_`s'=1 if est_`s'!=.
	****

if  "`var'"=="area_single" loc t "Approved permits for" "single-family homes (sqm)"
if "`var'"=="area_multi" loc t "Approved permits for" "multi-family homes (sqm)"

 
* top part-yscale
twoway (scatter  pos_1 est_1  , msize(medlarge)  msymbol(circle)   mcolor(gs1)) ///
	(rbar ci_low_1 ci_high_1 pos_1 , lwidth(vvthin)  fcolor(gs1) lcolor(gs1) lpattern(solid) horizontal barwidth(.015)) ///
	(scatter  pos_2 est_2  , msize(medlarge)  msymbol(circle)  mcolor(gs3)) ///
	(rbar ci_low_2 ci_high_2 pos_2 , lwidth(vvthin)  fcolor(gs3) lcolor(gs3) lpattern(solid) horizontal barwidth(.015)) ///
	(scatter  pos_3 est_3  , msize(medlarge)  msymbol(circle)  mcolor(gs5)) ///
	(rbar ci_low_3 ci_high_3 pos_3 , lwidth(vvthin)  fcolor(gs5) lcolor(gs5) lpattern(solid) horizontal barwidth(.015)) ///
	(scatter  pos_4 est_4  , msize(medlarge)  msymbol(circle)  mcolor(gs7)) ///
	(rbar ci_low_4 ci_high_4 pos_4 , lwidth(vvthin)  fcolor(gs7) lcolor(gs7) lpattern(solid) horizontal barwidth(.015)) ///
		(scatter  pos_5 est_5  , msize(medlarge)  msymbol(circle)  mcolor(gs9)) ///
	(rbar ci_low_5 ci_high_5 pos_5 , lwidth(vvthin)  fcolor(gs7) lcolor(gs9) lpattern(solid) horizontal barwidth(.015)) ///
	(scatter  pos_6 est_6  , msize(medlarge)  msymbol(circle)  mcolor(gs11)) ///
	(rbar ci_low_6 ci_high_6 pos_6 , lwidth(vvthin)  fcolor(gs7) lcolor(gs11) lpattern(solid) horizontal barwidth(.015)) ///
	,xline(0, lcolor(gs7) lpattern(dash)) yscale(range(0.5 6.5)) xtitle("") ///
	 ytitle(, size(zero)) ylabel(none)  scale(.7) ysize(20) xsize(20) scheme(s1mono) title("`t'") ///
	   xlabel(, angle(horizontal) grid) legend(on order(1 "No controls" 3  "Population composition" 5 "Turnout" 7 ///
	   "Economic Geography" 9 "Lagged outcome control" 11 "All controls") rows(1)  size(vsmall)) 
graph save reg_`treat'_`sample'_`var', replace

restore
	
		}
		}
		}

		
grc1leg reg_diff_vald_maj_bef_all_area_multi.gph reg_diff_vald_maj_bef_all_area_single.gph   , ///
	    ysize(7) xsize(40) col(2) iscale(1) scheme(s1mono) xcommon b1("Estimated effect of residential concentration of majority vs. population", size(small)) ring(2)
graph display,	ysize(15) xsize(22)	

graph export "$res\figA11.$e", replace  
	

log close
